package com.welkom.everydate.services.implementations;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.welkom.everydate.common.Constants;
import com.welkom.everydate.dao.MenuDao;
import com.welkom.everydate.dao.UserDao;
import com.welkom.everydate.domain.Authority;
import com.welkom.everydate.domain.Menu;
import com.welkom.everydate.domain.Role;
import com.welkom.everydate.domain.User;
import com.welkom.everydate.security.exception.UserNotFoundException;
import com.welkom.everydate.services.interfaces.MenuService;
import com.welkom.everydate.services.interfaces.ResourceService;
@Service
public class MenuServiceImpl implements MenuService {
	@Resource
	private UserDao userDao;
//	@Resource
//	private MenuDao menuDao;
	@Resource 
	private ResourceService resourceService;
	@Override
	public List<Menu> getMenusByUserName(String userName) {
		// TODO Auto-generated method stub
		User user=userDao.getUserByUserName(userName);
		if(user==null){
			throw new UserNotFoundException();
		}
		List<Long> authorityIds=new ArrayList<Long>();
		List<Role> roles=user.getRoles();
		for(Role role:roles){
			List<Authority> authoritiesInRole=role.getAuthorities();
			for(Authority authority:authoritiesInRole){
				if(!authorityIds.contains(authority)){
					authorityIds.add(authority.getAuthorityId());
				}
			}
		}
		List<Menu> menus=new ArrayList<Menu>();
		List<com.welkom.everydate.domain.Resource> resources=resourceService.getResourcesByAuthorityIds(authorityIds);
		for(com.welkom.everydate.domain.Resource resource:resources){
			if(resource.getResourceType()==Constants.ResourceType.RESOURCE_TYPE_MODULE_MENU||resource.getResourceType()==Constants.ResourceType.RESOURCE_TYPE_SECOND_MENU){
				Menu menu=new Menu();
				menu.setMenuName(resource.getResourceName());
				menu.setMenuId(resource.getResourceId());
				menu.setMenuDisplayClass(resource.getMenuStyleClass());
				menu.setMenuLevel(resource.getResourceType());
				menu.setMenuUrl(resource.getResourceString());
				menu.setParentMenuId(resource.getParentResourceId());
				menus.add(menu);
			}
		}
		return menus;
	}
	
	

}
